//页面级视图-存储卡读取权限
import React from 'react';
import {View, Alert} from 'react-native';
import {useDebounceEffect, useMount, useSafeState, useUnmount} from 'ahooks';
import {Text, Button} from '@rneui/base';
import {
  check,
  request,
  PERMISSIONS,
  openSettings,
  RESULTS,
} from 'react-native-permissions';
import style from './style.less';

export default ({children, callback}) => {
  const [storageReadStatusTxt, setStorageReadStatusTxt] = useSafeState();
  const isLoading = storageReadStatusTxt === undefined;
  const isAllow = storageReadStatusTxt === RESULTS.GRANTED;
  useMount(async () => {
    let v = '';
    try {
      v = await check(PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE);
    } catch (e) {
      v = 'denied';
    }
    setStorageReadStatusTxt(v);
  });
  useDebounceEffect(
    () => {
      callback?.();
    },
    [isAllow],
    {wait: 0},
  );
  if (isLoading) {
    return <></>;
  }
  if (!isAllow) {
    return (
      <>
        <View style={style.setPowerBox}>
          <Text>写存储卡权限</Text>
          <Button
            title="授权"
            buttonStyle={style.setPowerBtnButtonStyle}
            containerStyle={style.setPowerBtnContainer}
            titleStyle={style.setPowerBtnTitleStyle}
            onPress={async () => {
              callback?.();
              let v = '';
              try {
                v = await request(PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE);
              } catch (e) {
                Alert.alert('操作失败', e.message);
                return;
              }
              if (v !== RESULTS.GRANTED) {
                openSettings().catch(() =>
                  Alert.alert('操作失败', '打开系统设置'),
                );
              } else {
                setStorageReadStatusTxt(v);
              }
            }}
          />
        </View>
      </>
    );
  }
};
